<?php


namespace App\Controller\Frontend;


use App\Entity\PageTag;
use App\Utils\Traits\JsonTrait;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class TagController extends AbstractController {
    use JsonTrait;

    private $limit = 10;

    /**
     * 类别页
     * @param Request $request
     * @param EntityManagerInterface $em
     * @param PaginatorInterface $paginator
     * @Route("/tag/{value}", name="tag_page")
     * @return array|\Symfony\Component\HttpFoundation\Response
     */
    public function index (Request $request, EntityManagerInterface $em, PaginatorInterface $paginator) {
        $value = $request->get('value', null);
        if (is_null($value)) {
            $this->redirect('home_page');
        }

        $tag = $this->getDoctrine()->getRepository(PageTag::class)->findOneBy(['value' => $value]);
        if (!is_object($tag)) {
            return $this->redirectToRoute('not_found_page');
        }

        $dql = "SELECT p.id,p.title,p.thumbnail,p.publish_time,p.page_like,p.page_tags,p.summary,c.value as category,a.avatar,a.username,a.nickname
                from App\Entity\Page as p 
                left join App\Entity\PageCategory as c with p.page_category_id = c.id 
                left join App\Entity\AdminUser as a with p.admin_user_id = a.id 
                where p.status = 1 and JSON_CONTAINS(p.page_tags, '[".$tag->getId()."]', '$') = 1 order by p.id DESC ";

        $query = $em->createQuery($dql);
        $pagination = $paginator->paginate($query, $request->query->getInt('page', 1), $this->limit);

        // 获取对应标签
        $page_tags = $this->getDoctrine()->getRepository(PageTag::class)->findAllToArray();
        $pages = $pagination->getItems();
        foreach ($pages as &$page) {
            $items = [];
            foreach ($page['page_tags'] as $tag_id) {
                if (isset($page_tags[$tag_id])) {
                    array_push($items, $page_tags[$tag_id]);
                }
            }
            $page['page_tags'] = $items;
        }
        $pagination->setItems($pages);

        return $this->render('frontend/tag/list.html.twig', [
            'tag'   => $tag,
            'pagination' => $pagination,
        ]);
    }
}